from flask import Flask, request, jsonify
import hashlib
import datetime
import os
import config

app = Flask(__name__)


# MD5 编码函数
def calculate_md5(text, file):
    # 对传递的文字进行MD5编码
    text_md5 = hashlib.md5(text.encode('utf-8')).hexdigest()

    # 对传递的文件进行MD5编码
    file_md5 = hashlib.md5()
    with open(file, "rb") as f:
        while chunk := f.read(8192):
            file_md5.update(chunk)
    file_md5 = file_md5.hexdigest()

    return text_md5, file_md5


@app.route('/process/', methods=['POST'])
def process_request():
    try:
        # 获取传递的文字内容和文件
        text = request.form['text']
        file = request.files['file']

        # 临时保存上传的文件
        file_path = os.path.join("tmp", file.filename)
        file.save(file_path)

        # 计算 MD5 值
        text_md5, file_md5 = calculate_md5(text, file_path)

        # 获取当前时间
        current_time = datetime.datetime.now()
        response_data = {
            'current_year': [current_time.year, "current_year"],
            'current_month': [current_time.month, "current_month"],
            'current_day': [current_time.day, 'current_day'],
            'weekday': [current_time.strftime('%A'), 'weekday'],
            'current_hour': [current_time.hour, 'current_hour'],
            'current_minute': [current_time.minute, 'current_minute'],
            'current_second': [current_time.second, 'current_second'],
            'text_md5': [text_md5, 'text_md5'],
            'file_md5': [file_md5, 'file_md5'],
        }

        # 返回 JSON 数据
        return jsonify(response_data)
    except Exception as e:
        return jsonify({"error": str(e)}), 400


if __name__ == '__main__':
    # 创建tmp文件夹来保存上传的文件
    if not os.path.exists('tmp'):
        os.makedirs('tmp')

    app.run(host="0.0.0.0", port=12345, debug=True)
